﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WeProjectsModel;
using System.Web.Security;
using WeProjects.Filters;
using WeProjects.Helps;

namespace WeProjects.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class TaskController : Controller
    {
        private ProjectsDBEntities db = new ProjectsDBEntities();

        //
        // GET: /Task/

        public ActionResult Index()
        {
            var tasks = db.Tasks.Include(t => t.Project);
            return View(tasks.ToList());
        }

        //
        // GET: /Task/Details/5

        public ActionResult Details(int id ,int projectID)
        {
            Task task = db.Tasks.Find(id);
            if (task == null)
            {
                return HttpNotFound();
            }
            ViewBag.ProjectID = projectID;
            return View(task);
        }

        //
        // GET: /Task/Create

        public ActionResult Create(int id=0)
        {
            var project = db.Projects.Find(id);
            if (project == null)
            {
                return HttpNotFound();
            }
            ViewBag.projectTitle = project.Title;
            //加载本组成员
            ViewBag.projectMember = project.Members.ToList();
            ViewBag.ProjectID = project.ID;
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        //public ActionResult Create(int? id, string desc, string due, string resp, string comm)
        public ActionResult Create(Task task, string[] members)
        {
            ViewBag.ProjectID = task.ProjectID;

            if (ModelState.IsValid)
            {
                //task.Responsibility = member;
                db.Tasks.Add(task);
                db.SaveChanges();
                return RedirectToAction("Details", "Project", new { id = task.ProjectID });
            }            
            return View();
        }
        /// <summary>
        /// 文档库显示
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Files(int projectId,int taskId)
        {
            //只显示未添加的
            //var task = (from t in db.Tasks where t.ID == taskId select t).First();
            //var project=from p in db.Projects
                        //where p.ParentID==projectId
                        //where p.Members.Any(m=>m.ID==int.Parse(Membership.GetUser().ProviderUserKey.ToString()))

                        //var task=from i in db.Tasks
                        //         where i.Project.ParentID==projectId
                        //         where i.Project.Member.ID==int.Parse(Membership.GetUser().ProviderUserKey.ToString())
                        //         select i;


            var doc =(from d in db.Documents
                      where !d.Tasks.Any(t=>t.ID==taskId)
                      where d.Project!=null
                      select d).ToList();
            return View(doc);
        }
        /// <summary>
        /// 从文档库选择
        /// </summary>
        /// <param name="chkfile"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Upload(int[] chkfile,int projectId,int taskId)
        {
            //如果什么都没有选，直接提交的bug处理
            if(chkfile==null)
            {
                return RedirectToAction("Details/" + taskId);
            }
            foreach(var item in chkfile)
            {
                db.Database.ExecuteSqlCommand("insert into TaskDocuments(TaskID,DocumentID) values('" + taskId + "','" + item + "')");
            }
            return RedirectToAction("Details/" + taskId);
        }
        
        /// <summary>
        /// 删除一个文档关联，但物理文件未操做
        /// </summary>
        /// <param name="taskID">任务id</param>
        /// <param name="docID">文档id</param>
        /// <returns></returns>
        public ActionResult DeleteDoc(int taskID,int docID)
        {
            //此处的linq语句
            var task=db.Tasks.Find(taskID);
            db.Database.ExecuteSqlCommand("delete from TaskDocuments where TaskID='"+taskID+"' and DocumentID='"+docID+"'");
            return RedirectToAction("Details/" ,new {id=taskID,projectID=task.ProjectID});
        }

        //
        // POST: /Task/Create

        /// <summary>
        /// 新建一个任务
        /// </summary>
        /// <param name="id"></param>
        /// <param name="desc"></param>
        /// <param name="due"></param>
        /// <param name="resp"></param>
        /// <param name="comm"></param>
        /// <returns></returns>
        


        //
        // GET: /Task/Edit/5

        public ActionResult Edit(int id = 0)
        {
            Task task = db.Tasks.Find(id);
            if (task == null)
            {
                return HttpNotFound();
            }
            ViewBag.ProjectID = new SelectList(db.Projects, "ID", "Title", task.ProjectID);
            return View(task);
        }

        //
        // POST: /Task/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Task task)
        {
            if (ModelState.IsValid)
            {
                db.Entry(task).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Details", "Project", new { id = task.ProjectID });
            }
            ViewBag.ProjectID = new SelectList(db.Projects, "ID", "Title", task.ProjectID);
            return View(task);
        }

        //
        // GET: /Task/Delete/5

        public ActionResult Delete(int id = 0)
        {
            Task task = db.Tasks.Find(id);
            if (task == null)
            {
                return HttpNotFound();
            }
            return View(task);
        }

        //
        // POST: /Task/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            Task task = db.Tasks.Find(id);
            int? projectId = task.ProjectID;
            Utility.RemoveBelongs<Document>(task.Documents, db);
            db.Tasks.Remove(task);
            db.SaveChanges();
            return RedirectToAction("Details", "Project", new { id= projectId});
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}